<template>
	<view class="container">
		<view class="settlement-page">
			<view class="form-title">
				<text>费用结算结果</text>
			</view>
			
			<!-- Concise Summary Section -->
			<view class="concise-summary">
				<view v-for="(summary, name) in settlementResults" :key="name" class="summary-item">
					<text class="summary-text">
						{{name}}: {{summary.balance > 0 ? '应退还' : '应补交'}} ¥{{Math.abs(summary.balance).toFixed(2)}}
					</text>
				</view>
			</view>
			
			<!-- Toggle Details Button -->
			<button class="toggle-btn" @click="toggleDetails">
				{{ showDetails ? '隐藏明细' : '显示明细' }}
			</button>
			
			<!-- Detailed Information (Collapsible) -->
			<view v-if="showDetails" class="details-section">
				<view class="summary-section">
					<view class="summary-content">
						<text class="total-item">总场地费: ¥{{totalCourtFee}}</text>
						<text class="total-item">总球费: ¥{{totalShuttleFee}}</text>
						<text class="total-item">总费用: ¥{{totalCost}}</text>
						<text class="total-item">总垫付: ¥{{totalPaidAmount}}</text>
					</view>
				</view>
				
				<view class="settlement-results">
					<view v-for="(summary, name) in settlementResults" :key="name" class="participant-summary">
						<text class="participant-name">{{name}}</text>
						<view class="fee-details">
							<text>垫付: ¥{{summary.paid}}</text>
							<text>(场地费:¥{{summary.courtFee}}, 球费:¥{{summary.shuttleFee}})</text>
						</view>
						<view class="payment-details">
							<text>应付: ¥{{summary.shouldPay}}</text>
							<text class="balance" :class="{'positive': summary.balance > 0, 'negative': summary.balance < 0}">
								{{summary.balance > 0 ? '需退还' : '需补交'}} ¥{{Math.abs(summary.balance).toFixed(2)}}
							</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- Add remarks display section -->
			<view v-if="remarks" class="remarks-section">
				<text class="remarks-title">备注信息：</text>
				<text class="remarks-content">{{remarks}}</text>
			</view>
			
			<view class="button-group">
				<button class="back-btn" @click="goBack">返回首页</button>
				<button class="share-btn" open-type="share">
					<text class="share-icon">📱</text>
					分享到微信
				</button>
			</view>
		</view>
		<canvas canvas-id="shareCanvas" style="position: fixed; left: -9999px; width: 300px; height: 500px;"></canvas>
	</view>
</template>

<script>
export default {
	data() {
		return {
			settlementResults: {},
			totalCourtFee: 0,
			totalShuttleFee: 0,
			totalCost: 0,
			totalPaidAmount: 0,
			showDetails: false,
			shareImagePath: '', // 用于保存生成的图片路径
			remarks: '' // 添加备注字段
		}
	},
	onLoad(option) {
		const data = JSON.parse(decodeURIComponent(option.data))
		this.settlementResults = data.settlementResults
		this.totalCourtFee = data.totalCourtFee
		this.totalShuttleFee = data.totalShuttleFee
		this.totalCost = data.totalCost
		this.totalPaidAmount = data.totalPaidAmount
		this.remarks = data.remarks || '' // 获取备注信息
	},
	methods: {
		goBack() {
			// 使用reLaunch替代navigateBack，确保能返回首页
			uni.reLaunch({
				url: '/pages/index/index',
				success: () => {
					console.log('返回首页成功');
				},
				fail: (err) => {
					console.error('返回首页失败:', err);
					// 如果reLaunch失败，尝试使用switchTab（如果首页在tabBar中）
					uni.switchTab({
						url: '/pages/index/index'
					});
				}
			});
		},
		toggleDetails() {
			this.showDetails = !this.showDetails
		},
		async generateShareImage() {
			return new Promise((resolve, reject) => {
				const ctx = uni.createCanvasContext('shareCanvas', this);

				// 设置背景颜色
				ctx.setFillStyle('#ffffff');
				ctx.fillRect(0, 0, 300, 500);

				// 设置标题
				ctx.setFontSize(18);
				ctx.setFillStyle('#000000');
				ctx.fillText('费用结算结果', 20, 30);

				// 绘制结算结果
				let yOffset = 60;
				for (const [name, summary] of Object.entries(this.settlementResults)) {
					const action = summary.balance > 0 ? '应退还' : '应补交';
					const amount = Math.abs(summary.balance).toFixed(2);
					ctx.fillText(`${name}: ${action} ¥${amount}`, 20, yOffset);
					yOffset += 20;
				}

				// 绘制总费用
				ctx.fillText(`总场地费: ¥${this.totalCourtFee}`, 20, yOffset + 20);
				ctx.fillText(`总球费: ¥${this.totalShuttleFee}`, 20, yOffset + 40);
				ctx.fillText(`总费用: ¥${this.totalCost}`, 20, yOffset + 60);
				ctx.fillText(`总垫付: ¥${this.totalPaidAmount}`, 20, yOffset + 80);

				// 绘制完成
				ctx.draw(false, () => {
					// 将 Canvas 保存为图片
					uni.canvasToTempFilePath({
						canvasId: 'shareCanvas',
						success: (res) => {
							this.shareImagePath = res.tempFilePath;
							resolve();
						},
						fail: (err) => {
							console.error('生成图片失败:', err);
							reject(err);
						}
					}, this);
				});
			});
		}
	},
	onShareAppMessage() {
		// 生成图片
		this.generateShareImage();

		// 分享图片
		return {
			title: '费用结算结果',
			imageUrl: this.shareImagePath, // 分享的图片路径
			success: () => {
				uni.showToast({
					title: '分享成功',
					icon: 'success'
				});
			},
			fail: (err) => {
				console.error('分享失败:', err);
				uni.showToast({
					title: '分享失败',
					icon: 'none'
				});
			}
		};
	}
}
</script>

<style>
.container {
	padding: 20rpx;
}

.settlement-page {
	background-color: #fff;
	border-radius: 10rpx;
	padding: 20rpx;
}

.form-title {
	font-size: 36rpx;
	font-weight: bold;
	text-align: center;
	margin-bottom: 30rpx;
}

.concise-summary {
	background-color: #fff;
	padding: 20rpx;
	border-radius: 8rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
}

.summary-item {
	padding: 15rpx 0;
	border-bottom: 1px solid #f0f0f0;
}

.summary-item:last-child {
	border-bottom: none;
}

.summary-text {
	font-size: 32rpx;
	color: #333;
	font-weight: 500;
}

.toggle-btn {
	background-color: #f5f5f5;
	color: #666;
	border: none;
	padding: 15rpx 30rpx;
	border-radius: 8rpx;
	margin: 20rpx 0;
	font-size: 28rpx;
}

.summary-section {
	background-color: #f8f8f8;
	padding: 20rpx;
	border-radius: 8rpx;
	margin-bottom: 30rpx;
}

.summary-content {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
}

.total-item {
	font-size: 32rpx;
	font-weight: bold;
}

.settlement-results {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.participant-summary {
	background-color: #f8f8f8;
	padding: 20rpx;
	border-radius: 8rpx;
}

.participant-name {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.fee-details, .payment-details {
	display: flex;
	flex-direction: column;
	gap: 5rpx;
	margin-top: 10rpx;
}

.balance {
	font-weight: bold;
	margin-top: 5rpx;
}

.balance.positive {
	color: #34C759;
}

.balance.negative {
	color: #FF3B30;
}

.button-group {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
	margin-top: 40rpx;
}

.back-btn {
	background-color: #007AFF;
	color: #fff;
	border: none;
	padding: 20rpx;
	border-radius: 8rpx;
	width: 100%;
	font-size: 32rpx;
}

.share-btn {
	background-color: #07C160;
	color: #fff;
	border: none;
	padding: 20rpx;
	border-radius: 8rpx;
	width: 100%;
	font-size: 32rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.share-icon {
	margin-right: 10rpx;
}

.details-section {
	color: #FF3B30;
}

.back-btn {
	background-color: #007AFF;
	color: #fff;
	border: none;
	padding: 20rpx;
	border-radius: 8rpx;
	margin-top: 40rpx;
	width: 100%;
	font-size: 32rpx;
}

.remarks-section {
	margin: 20rpx 0;
	padding: 20rpx;
	background-color: #f8f8f8;
	border-radius: 8rpx;
}

.remarks-title {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 10rpx;
	display: block;
}

.remarks-content {
	font-size: 28rpx;
	color: #333;
	line-height: 1.4;
}

.details-section {
	animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(-10rpx);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}
</style>